package edu.nf.project.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author CSY
 * @date 2025 - 06 - 16
 * 文件上传工具类
 *
 */
public class FileUploadUtil {

    /**
     * 文件上传方法
     * @param file 要上传的文件(MultipartFile类型)
     */
    public static String fileUpload(MultipartFile file) {
        try {
            // 生成唯一文件名
            String originalFileName = file.getOriginalFilename();
            String uniqueFileName = generateUniqueFileName(originalFileName);

            // 将MultipartFile临时保存为本地文件
            File tempFile = convertMultipartFileToTempFile(file, uniqueFileName);

            // 填写您的AccessKey ID和AccessKey Secret
            String accessKeyId = "LTAI5tKFf9cjiA8hzS8Sq8Cu";
            String accessKeySecret = "DFIaG9jTtuKrM9pvda7T0TBT2NQrBt";
            // 填写Bucket名称
            String bucketName = "rsl-plus";
            // 无地域的Endpoint
            String endpoint = "oss-rg-china-mainland.aliyuncs.com";

            // 创建OSSClient实例
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            // 使用V2签名
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V2);
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, clientBuilderConfiguration);

            try {
                // 创建PutObjectRequest对象
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, tempFile);
                // 上传文件
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                System.out.println("文件上传成功！");
                //将最终文件名返回出去以供存入数据库
                return uniqueFileName;
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
                throw oe;
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
                throw ce;
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
                // 清理临时文件
                if (tempFile != null && tempFile.exists()) {
                    tempFile.delete();
                }
            }
        } catch (IOException e) {
            System.out.println("文件处理失败：" + e.getMessage());
            throw new RuntimeException("文件处理失败", e);
        }
    }

    /**
     * 将MultipartFile转换为临时文件
     */
    private static File convertMultipartFileToTempFile(MultipartFile file, String fileName) throws IOException {
        File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName);
        file.transferTo(tempFile);
        return tempFile;
    }

    /**
     * 使用UUID+时间戳生成唯一的文件名
     * @param originalFileName 文件名
     * @return
     */
    private static String generateUniqueFileName(String originalFileName) {
        // 获取文件扩展名
        String extension = "";
        int lastIndexOf = originalFileName.lastIndexOf('.');
        if (lastIndexOf > 0) {
            extension = originalFileName.substring(lastIndexOf);
        }

        // 生成UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 添加时间戳（可选，提高可读性）
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        // 组合新文件名：时间戳+UUID+扩展名
        return timestamp + "_" + uuid + extension;
    }
}